<template>
  <div class="ele-body">
    <el-card shadow="never">

      <!-- 查询 -->
      <el-popover ref="search" placement="bottom" offset="0" @hide="clearForm">
        <template>
          <el-form ref="form" :model="where" label-width="100px">

            <el-form-item label="级别：" prop="grade_id">
              <el-select v-model="where.grade_id" placeholder="请选择">
                <el-option
                    v-for="item in grades"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="学部：" prop="dept_type">
              <el-select v-model="where.dept_type" placeholder="请选择">
                <el-option
                    v-for="item in deptTypes"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="班级名称：" prop="name">
              <el-input v-model="where.name" placeholder="请输入名称" clearable/>
            </el-form-item>

            <el-form-item>
              <div class="ele-form-actions">
                <el-button type="primary" @click="query" icon="el-icon-search" class="ele-btn-icon">查询</el-button>
                <el-button @click="(where={})&&$refs.classTable.reload()">重置</el-button>
              </div>
            </el-form-item>

          </el-form>
        </template>
      </el-popover>

      <!-- 操作按钮 -->
      <div class="ele-table-tool ele-table-tool-default">
      <!-- TODO 可以使用Popover 弹出框优化 -->
        <el-button v-popover:search type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small">查询</el-button>
        <el-button @click="showCreateGradeForm=true" type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small">新建年级</el-button>
        <el-button @click="remove()" type="danger" icon="el-icon-delete" class="ele-btn-icon" size="small">批量删除</el-button>
        <el-button @click="quickUpgrade=true" type="primary" icon="el-icon-plus" class="ele-btn-icon" size="small">一键升年级</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table ref="classTable" :data="data" row-key="id" default-expand-all border
                height="calc(100vh - 215px)" highlight-current-row>

        <el-table-column type="selection" width="55" />

        <el-table-column label="编号" type="index" width="60" align="center" fixed="left"/>

        <el-table-column label="组树" show-overflow-tooltip min-width="50">
          <template slot-scope="{row}">{{ row.name }}</template>
        </el-table-column>

        <el-table-column prop="school_year" label="级别" show-overflow-tooltip width="80"/>

        <el-table-column prop="dept_name" label="学部" show-overflow-tooltip min-width="50"/>

        <el-table-column prop="worker_name" label="负责人" show-overflow-tooltip min-width="100"/>

        <el-table-column prop="note" label="备注" min-width="50" align="center"/>

        <el-table-column label="操作" width="300px" align="center" :resizable="false"  fixed="right">
          <template slot-scope="{row}">
            <el-link v-if="row.type === 0" @click="add(row)" icon="el-icon-plus" type="primary" :underline="false">添加班级</el-link>
            <el-link @click="edit(row)" icon="el-icon-edit" type="primary" :underline="false">修改</el-link>
            <el-popconfirm title="确定要删除此班级吗？" @confirm="remove(row)" class="ele-action">
              <el-link slot="reference" icon="el-icon-delete" type="danger" :underline="false">删除</el-link>
            </el-popconfirm>
          </template>
        </el-table-column>

      </el-table>


    </el-card>
    <!-- 编辑弹窗 -->
    <el-dialog :title="createClassForm.id?'修改班级':'添加班级'" :visible.sync="showEdit" width="800px"
               @closed="createClassForm={};controlCustomButton=true" :destroy-on-close="true" :lock-scroll="false" @open="dialogOpen">
      <el-form :model="createClassForm" ref="editClassForm" :rules="editRules" label-width="100px">

        <el-form-item label="所属年级：" prop="grade_name">
            <el-input v-model="createClassForm.grade_name" placeholder="请输入名称" :disabled="true"/>
        </el-form-item>

        <el-row class="el-row" :gutter="5">
          <el-col :span="10" >
            <el-form-item label="班级：" prop="sequence">
              <el-input v-model="createClassForm.sequence" placeholder="请输入名称" clearable @input="changeClassName">
                <template slot="prepend">年级名称</template>
                <template slot="append">班</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="班级名称：" prop="name">
              <el-input v-model="createClassForm.name" placeholder="请输入名称" :disabled="controlCustomButton" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="controlCustomButton = false">自定义</el-button>
          </el-col>
        </el-row>

        <div v-for="(item, index) in createClassForm.dynamicItem" :key="index">
          <el-row class="el-row">
            <el-col :span="6">
              <el-form-item
                  label="负责人"
                  :prop="'dynamicItem.' + index + '.worker_id'"
                  :rules="{required: true, message: '负责人不能为空', trigger: 'blur'}"
                  :key="item.key"
              >
                <el-select v-model="item.worker_id" placeholder="请选择负责人" class="ele-block" clearable>
                  <el-option
                      v-for="item in workers"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item
                  label="职务"
                  :prop="'dynamicItem.' + index + '.duty_code'"
                  :rules="{required: true, message: '职务不能为空', trigger: 'blur'}"
                  :key="item.key"
              >
                <el-select v-model="item.duty_code" placeholder="请选择职务" class="ele-block" clearable>
                  <el-option
                      v-for="item in dutys"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code + ':' + item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item
                  label="科目"
                  :prop="'dynamicItem.' + index + '.subject_code'"
                  :rules="{required: true, message: '科目不能为空', trigger: 'blur'}"
                  :key="item.key"
              >
                <el-select v-model="item.subject_code" placeholder="请选择职务" class="ele-block" clearable>
                  <el-option
                      v-for="item in subjects"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code + ':' + item.name">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item>
                <el-button type="danger" icon="el-icon-delete" @click="deleteItem(item, index)" round></el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <el-row class="el-row">
          <el-col :span="6" :offset="20">
            <el-button @click="addItem" type="primary">添加负责人</el-button>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="note">
          <el-input type="textarea"
                    :rows="2" v-model="createClassForm.note" placeholder="请输入备注" clearable/>
        </el-form-item>
                              
      </el-form>
      <div slot="footer">
        <el-button @click="showEdit=false">取消</el-button>
        <el-button type="primary" @click="save">保存</el-button>
      </div>
    </el-dialog>

    <search :showSearchGradeForm.sync="showSearchGradeForm"></search>
    <create-grade :showCreateGradeForm.sync="showCreateGradeForm" @reload="query()" :id="grade_id_for"></create-grade>
    <upgrade :showUpgradeForm.sync="quickUpgrade"></upgrade>
  </div>
</template>

<script>
import Search from "./search";
import CreateGrade from "./create-grade";
import upgrade from "./upgrade";
export default {
  name: "SchoolClasses",
  components: {Search,CreateGrade,upgrade},
  data() {
    return {
      loading: true,  // 加载状态
      data: [],  // 列表数据
      where: {},  // 搜索条件
      workers: [], // 所有教职工
      dutys: [], // 所有教职工职务
      subjects: [], // 所有科目
      showEdit: false,  // 是否显示表单弹窗
      showCreateGradeForm: false, // 是否显示创建年级弹窗
      showSearchGradeForm: false, // 是否显示搜索弹窗
      quickUpgrade: false, // 一键升年级弹窗
      controlCustomButton: true, // 控制自定义按钮失效
      createClassForm: {
        dynamicItem: [] // 动态表单项
      },  // 表单数据
      editRules: {  // 表单验证规则

        sequence: [
          {required: true, message: '请输入班级序号', trigger: 'blur'}
        ],

        name: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
              
      },
      grades: [], // 级别，即届数
      deptTypes: [], // 学部
      grade_id_for: 0
    }
  },
  mounted() {
    this.query();
  },
  methods: {
    /* 查询 */
    query() {
      this.loading = true;
      this.$http.get('/classes/list', {params: this.where}).then(res => {
        this.loading = false;
        this.data = res.data;
      }).catch(e => {
        this.loading = false;
        this.$message.error(e.message);
      });
    },
    /* 显示添加 */
    add(row) {
      this.createClassForm = {grade_id: row ? row.id.split('-')[1] : null, grade_name: row ? row.name : null, dynamicItem: []};
      this.showEdit = true;
    },
    /**
     * 显示编辑
     */
    edit(row) {

      if(row.type === 0) { // 为年级
        this.grade_id_for = parseInt(row.id.split('-')[1]);
        this.showCreateGradeForm = true;
      } else {
        this.$http.get('/classes/info?id=' + row.id).then(res => {
          if (res.data.code === 200) {
            this.createClassForm = res.data.result; // https://www.jianshu.com/p/64fdafc983d2
            this.createClassForm.dynamicItem = []; // TODO 需要完善
            this.showEdit = true;
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          this.$message.error(e.message);
        });
      }
    },
    /**
     * 保存编辑
     */
    save() {
      this.$refs['editClassForm'].validate((valid) => {
        if (valid) {
          const loading = this.$loading({lock: true});
          this.$http.post('/classes/edit', this.createClassForm).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.showEdit = false;
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        } else {
          return false;
        }
      });
    },
    /**
     * 刪除(批量刪除)
     */
    remove(row) {
      console.log(row)
      if (!row) {  // 批量删除
        if (this.choose.length === 0) return this.$message.error('请至少选择一条数据');
        let ids = this.choose.map(d => d.id);
        // TODO 需要区分年级和班级分别进行删除
        this.$confirm('确定要删除选中的班级吗?', '提示', {type: 'warning'}).then(() => {
          const loading = this.$loading({lock: true});
          this.$http.post('/classes/delete', {id: ids}).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        }).catch(() => 0);
      } else {  // 单个删除
        const loading = this.$loading({lock: true});

        if(row.type === 0) { // 为年级
          this.$http.post('/grade/delete', {id:row.id.split('-')[1]}).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        } else {
          this.$http.post('/classes/delete', {id:row.id}).then(res => {
            loading.close();
            if (res.data.code === 200) {
              this.$message({type: 'success', message: res.data.msg});
              this.query();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        }
      }
    },
    addItem () {
      this.createClassForm.dynamicItem.push({
        worker_id: '',
        duty_code: '',
        subject_code: '',
        key: Date.now(),
      })
      this.$forceUpdate();
    },
    deleteItem (item, index) {
      this.createClassForm.dynamicItem.splice(index, 1)
    },
    /**
     * 清理查询表单
     */
    clearForm() {
      this.where = {};
    },
    /**
     * 获取所有教职工
     */
    getWorkers() {
      this.$http.get('/worker/getWorkersIdName').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.workers = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取教职工角色 TODO 应该从角色表中获取
     */
    getDutys() {
      this.$http.get('/dictType/class_duty_code').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.dutys = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 获取所有科目
     */
    getSubjects() {
      this.$http.get('/dictType/subject_code').then(res => {
        this.loading = false;
        if (res.data.code === 200) {
          this.subjects = res.data.result;
        } else {
          this.$message.error(res.data.msg || '获取数据失败');
        }
      }).catch(e => {
        this.$message.error(e.message);
      });
    },
    /**
     * 对话框弹出时回调方法
     */
    dialogOpen() {
      this.getWorkers();
      this.getDutys();
      this.getSubjects();
    },
    changeClassName(value) {
      this.createClassForm.name = this.createClassForm.grade_name + '('+ value + ')班'
    }
  },

}
</script>

<style scoped>
.ele-block >>> .el-upload, .ele-block >>> .el-upload-dragger {
  width: 100%;
}
.el-row {
  margin-bottom: 20px;
  display: flex;
  flex-wrap: wrap
}
</style>